package com.crm.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crm.entity.User;
import com.crm.repository.UserRepository;
import com.crm.service.UserService;
import com.crm.util.CaptchaUtil;
import com.crm.util.MD5;
import com.crm.util.RedisUtil;
import com.crm.util.ResultInfoUtil;
import com.crm.util.TokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sun.xml.internal.xsom.impl.scd.Iterators.Map;

@RestController
@RequestMapping("login")
@CrossOrigin
public class LoginController {
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserService userServce;
	@Autowired
	private RedisUtil redisUtil;
	
	 private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
	   //用来保存得到的验证码
	   String code="";
		 
		  /**
		   * 生成验证码
		 * @throws IOException 
		   */
	      @GetMapping(value = "/getVerify")
		  public void getVerify(HttpServletRequest request, HttpServletResponse response) throws IOException  {
			  response.setHeader("Expires", "-1");  
		        response.setHeader("Cache-Control", "no-cache");  
		        response.setHeader("Pragma", "-1");  
		        CaptchaUtil util = CaptchaUtil.Instance();  
		        // 将验证码输入到session中，用来验证  
		         code = util.getString();  
		        System.out.println("-----------"+code);
		        request.getSession().setAttribute("code", code);  
		        // 输出打web页面  
		        ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
		  }
	     @GetMapping(value = "/checkVerify")
		 public boolean checkVerify(String verifyInput) {
			 if(code.equalsIgnoreCase(verifyInput)) {
				 return true;
			 }else {
				 return false;
			 }
			 
		 }
		  /**
		   * 校验验证码
		   */
		//  @GetMapping(value = "/checkVerify")
		//  public boolean checkVerify(String verifyInput, HttpSession session) {
		//    try{
		      //从session中获取随机数
		 //     String inputStr = verifyInput;
//		      String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
		 //     if (random == null) {
		 //       return false;
		 //     }
		 //     if (random.equals(inputStr)) {
		   //     return true;
		  //    } else {
		   //     return false;
		   //   }
		//    }catch (Exception e){
		 //     logger.error("验证码校验失败", e);
		 //     return false;
		 //   }
		//  }
	
	
	@GetMapping("/login")
	public Object login(String userName,String userPassWord,String yzm) {
		 if(!code.equalsIgnoreCase(yzm)) {
			 System.out.println(yzm+"0000000");
			 return new ResultInfoUtil(-1, "验证码错误！", null);
		 }else {
			//获取subject操作主体
				Subject subject=SecurityUtils.getSubject();
				//设置登录的用户名密码
				UsernamePasswordToken token=new UsernamePasswordToken(userName,MD5.JiaM(userPassWord));
				
				//用来存token
		    	String tk=null;
		    	//自定义一个用户，用于生产token
				User u = new User();
				u.setUserName(userName);
				List<String> ynGt5 = userRepository.YNGt5();
				String id = userRepository.findId(userName);
				if(!ynGt5.contains(id)) {
					try {
						subject.login(token);
						token.isRememberMe();
						//token
			    		try {
							tk = TokenUtil.sign(u, 1 * 60 * 60 * 1000);
							userRepository.lastLoginTime(userName);
							redisUtil.set(u.getUserName(),tk,1 * 60 * 60 * 1000);
							System.out.println("token:"+tk);
						} catch (UnsupportedEncodingException | JsonProcessingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			    		
						return new ResultInfoUtil(0, tk, subject.getPrincipal());
					}catch (UnknownAccountException e) {		
						userServce.updateIsLockOut(userName);
						return new ResultInfoUtil(-1, "用户名不正确！", null);
					}catch (IncorrectCredentialsException e) {		
						userServce.updateIsLockOut(userName);
						return new ResultInfoUtil(-1, "密码不正确！", null);
					}
				}else {
					 Integer integer = userRepository.AutoJiefeng2(userName);
			            String autoJieFeng = userRepository.AutoJieFeng(userName);
			            if(autoJieFeng!=null){
			                String lockout1="0";
			                String cishu1="0";
			                String id1 = userRepository.findId(userName);
			                userRepository.updateIsLockOut(lockout1,cishu1,id1);
			                return new ResultInfoUtil(-1, "账号已解封！", null);
			            }
			            if(integer==5){
			                String lockout1="1";
			                String cishu1="5";
			                String id1 = userRepository.findId(userName);
			                userRepository.updateIsLockOut(lockout1,cishu1,id1);
			                userServce.Updatelockwrotime(userName);//修改时间
			                userServce.updateIsLockOut(userName);//增加一次错误次数
			               
			                return new ResultInfoUtil(-1, "账号已被封禁！", null);
			            } 
			            return new ResultInfoUtil(-1, "请留意官方消息！", null);
				} 
		 
		 }
			
		
		
		

		
		
	}
	@RequiresRoles(value = "admin")//这个借口必须是admin角色才可以访问
	@GetMapping("/role")
	public Object testRole() {
		return "拥有admin角色";
	}
	@RequiresPermissions(value="user:add")//这个借口必须有user：add权限才可以访问
	@GetMapping("/permission")
	public Object testPermission() {
		return "拥有add权限";
	}
	@GetMapping("/unauthorized")
	public Object unauthorized() {
		return "您没有权限";
	}
	

	
}
